package BussinessLayer;

import DTO.Member.MemberList;
import java.lang.*;
import DTO.Member.Members;
import DTO.Report.ReportList;
import DTO.Report.Reports.ReportsFields;
import DataAccessLayer.MembersSql;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class MembersFactory {

    MembersSql _dataObject = null;

    public MembersFactory() {
        _dataObject = new MembersSql();
    }

    public Boolean Insert(Members businessObject) {
        return _dataObject.Insert(businessObject);
    }

    public Boolean Update(Members businessObject) {
        return _dataObject.Update(businessObject);
    }

    public Members GetByPrimaryKey(int keys) {
        return _dataObject.SelectByPrimaryKey(keys);
    }

    public List<Members> GetAll() {
        return _dataObject.SelectAll();
    }

    public List<Members> GetAllBy(Members.MembersFields fieldName, Object value) {
        return _dataObject.SelectByField(fieldName.toString(), value);
    }

    public int GetMaxId() {
        return _dataObject.GetMaxId();
    }

    public String GetTreeJSON(String strRootNamespace) {
//        List<Members> lstMemList;
//        try {
//            lstMemList = _dataObject.GetSubTree(strRootNamespace);
//        } catch (Exception ex) {
//            return "";
//        }
        String strJson = "[";
//        Members memRoot = new Members();
//
//        try {
//            memRoot = lstMemList.Where(m = >  m.NameSpace.Equals(strRootNamespace)).First();
//        } catch (Exception ex) {
//            memRoot = new Members();
//            memRoot.FullName = "Root";
//        }
//
//        strJson += " { \"title\": '" + memRoot.FullName
//                + (!memRoot.FullName.equals("Root")
//                ? (" (MSTV: " + memRoot.MemCode + ")")
//                : "")
//                + "', \"icon\": false, ";
//        strJson += " \"namespc\": '" + memRoot.NameSpace + "', ";
//        strJson += " \"key\": '" + memRoot.MemId + "', ";
//        strJson += " \"tooltip\": '" + memRoot.FullName + "' ";
//        strJson += GetChildrenJSON(lstMemList, memRoot.NameSpace);
//        strJson += "}]";
//        strJson = strJson.replace(",]", "]").replace(",}", "}");
//
        return strJson;
    }

    private static String GetChildrenJSON(List<Members> lstMemList, String strNs) {
//        List<Members> lstChildList;
//
//        if (String.IsNullOrEmpty(strNs)) // lay tat ca cac node tang 1
//        // co namespace khong chua dau '.'
//        {
//            lstChildList = lstMemList.Where(m = > ! m.NameSpace.Contains(".")).ToList();
//        } else // lay tat ca cac con truc tiep
//        // co namespace bat dau bang 'strNs.' va co so dau cham bang so dau cham cua strNs + 1
//        {
//            lstChildList = lstMemList.Where(m = >  (m.NameSpace.IndexOf(strNs + ".") > -1)
//                    && (m.NameSpace.Count(d = >  d.Equals('.')) == (strNs.Count(d = >  d.Equals('.')) + 1))).ToList();
//        }
//
        String strJson = "";
//        strJson += ", \"children\":";
//        strJson += "[";
//        // chay qua moi con truc tiep de lay thong tin
//
//        foreach(var
//        child in lstChildList)
//        {
//            strJson += " { \"title\": '" + child.FullName + " (MSTV: " + child.MemCode + ")', \"icon\": false, ";
//            strJson += " \"namespc\": '" + child.NameSpace + "', ";
//            strJson += " \"key\": '" + child.MemId + "', ";
//            strJson += " \"tooltip\": '" + child.FullName + "' ";
//            // chay de quy
//            strJson += GetChildrenJSON(lstMemList, child.NameSpace);
//            strJson += "},";
//        }
        strJson += "]";

        return strJson;
    }

    public List<Members> GetNameSpace(String nameSpace) {
        //public void GetNameSpace(String nameSpace,List<Members> listmem) {
        List<Members> members = new ArrayList<Members>();
        members = _dataObject.GetSubTree(nameSpace);
        return members;
    }

    public String RemoveSign4VietnameseString(String str) {
        String[] VietnameseSigns = new String[]{
            "aAeEoOuUiIdDyY",
            "áàạảãâấầậẩẫăắằặẳẵ",
            "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",
            "éèẹẻẽêếềệểễ",
            "ÉÈẸẺẼÊẾỀỆỂỄ",
            "óòọỏõôốồộổỗơớờợởỡ",
            "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",
            "úùụủũưứừựửữ",
            "ÚÙỤỦŨƯỨỪỰỬỮ",
            "íìịỉĩ",
            "ÍÌỊỈĨ",
            "đ",
            "Đ",
            "ýỳỵỷỹ",
            "ÝỲỴỶỸ"};
//        for (int i = 1; i < VietnameseSigns.length; i++) {
//            for (int j = 0; j < VietnameseSigns[i].length(); j++) {
//                str = str.replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
//            }
//        }
        return str;
    }

    public void genXmlFromDB(Members member, String realPath) {
        //memberFac = new MembersFactory();
        MemberList memberList = new MemberList();
        MembersFactory memfac = new MembersFactory();        
        ReportList reportList = new ReportList();
        ReportsFactory reportFac = new ReportsFactory();
        if (member.getMemCode().toLowerCase().trim().equals("admin")) {
            memberList.setMember(memfac.GetAll());
            reportList.setReport(reportFac.GetAll());
        } else {
            memberList.setMember(memfac.GetNameSpace(member.getNameSpace()));
            reportList.setReport(reportFac.GetAllBy(ReportsFields.MemId_Rev, member.getMemId()));
        }
        int lenght = reportList.getReport().size();
        for (int idex = 0; idex < lenght; idex++) {
            Members newMember = new Members();
            int memRev = Integer.parseInt(reportList.getReport().get(idex).getMemIdRev().toString());
            int memSend = Integer.parseInt(reportList.getReport().get(idex).getMemIdSend().toString());
            MembersFactory memFacto = new MembersFactory();
            newMember = memFacto.GetByPrimaryKey(memRev);
            reportList.getReport().get(idex).setFullNameRev(newMember.getFullName().trim());
            memFacto = new MembersFactory();
            newMember = memFacto.GetByPrimaryKey(memSend);
            reportList.getReport().get(idex).setFullNameSend(newMember.getFullName().trim());
        }
        try {
            JAXBContext ctx = JAXBContext.newInstance(memberList.getClass());
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            mar.marshal(memberList, new File(realPath + "members" + member.getMemCode() + ".xml"));
            ctx = JAXBContext.newInstance(reportList.getClass());
            mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(reportList, new File(realPath + "reports" + member.getMemCode() + ".xml"));
        } catch (JAXBException ex) {
        }
    }
}
